package com.shh.aiojbackendserver.utils;



import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * token工具类
 */

@Component
public class JwtUtil {
    /**
     * 设置有效期为 60 * 60 秒
     */
    private static final Long JWT_TTL = 3600000L;
    /**
     * 设置秘钥明文
     */
    private static final String JWT_KEY= "abcdfghabcdfghiabcdfghiabcdfghijklmnopqrstuvwxyzasdasdasfasdfdsfsdfasdasdasdassfsadfgtjhytjtyjtyjuytj";


    /**
     * 生成token
     * @param username
     * @param r_id
     * @return
     */
    public static String generateToken(String username,Long r_id){
        Date now = new Date();
        Date expiration = new Date(now.getTime() + 1000 + JWT_TTL);
        System.out.println("传进来generateToken的r_id为" + r_id);
        return Jwts.builder()
                .setHeaderParam("type","JWT")
                .setSubject(username)
                .setId(String.valueOf(r_id))
                .setExpiration(expiration)
                .signWith(SignatureAlgorithm.HS512,JWT_KEY)
                .compact();
    }

    /**
     * 解析token
     * @param token
     * @return
     */
    public static Claims getClaimsByToken(String token){
        return Jwts.parser()
                .setSigningKey(JWT_KEY)
                .parseClaimsJws(token)
                .getBody();
    }
}